package com.cskaoyan.service.systemservice;

import com.cskaoyan.bean.mallbean.Storage;
import com.cskaoyan.bean.mallbean.StorageExample;
import com.cskaoyan.mapper.mallmapper.StorageMapper;
import com.cskaoyan.vo.systemvo.StorageListVo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class StorageServiceImpl implements StorageService {
    @Autowired
    StorageMapper storageMapper;


    @Override
    public StorageListVo list(Integer page, Integer limit, String key,String name, String sort, String order) {
//        PageHelper.startPage(page, limit);

        StorageExample storageExample = new StorageExample();
        StorageExample.Criteria criteria = storageExample.createCriteria();
        //检查key
        if (key != null && !"".equals(key)) {
            criteria.andKeyLike("%" + key + "%");
        }

        //检查name
        if (name != null && !"".equals(name)) {
//            StorageExample.Criteria criteria = storageExample.createCriteria();
            criteria.andNameLike("%" + name + "%");
        }

        storageExample.setOrderByClause(sort + " " + order);

        //数据集
        List<Storage> storages = storageMapper.selectByExample(storageExample);
        StorageListVo storageListVo = new StorageListVo();
        int size = storages.size();
        storageListVo.setTotal(size);
        //设置pageHelper
        int startIndex = (page-1)*limit;
        int endIndex = (size-startIndex)>limit?(startIndex+limit):(size);
        ArrayList<Storage> storages1 = new ArrayList<>();
        for (int i = startIndex; i <endIndex ; i++) {
            storages1.add(storages.get(i));

        }


        storageListVo.setItems(storages1);


        return storageListVo;


    }

    /**
     * 只能更改名称
     *
     * @param storage
     * @return
     */
    @Override
    public Storage update(Storage storage) {
        //拿到id 和name
        Storage storage1 = new Storage();
        storage1.setId(storage.getId());
        storage1.setName(storage.getName());

        storageMapper.updateByPrimaryKeySelective(storage1);

        //返回storage
        Storage storage2 = storageMapper.selectByPrimaryKey(storage.getId());
        return storage2;
    }

    /**
     * 删除
     *
     * @param storage
     */
    @Override
    public void delete(Storage storage) {
        //物理删除
        storageMapper.deleteByPrimaryKey(storage.getId());
//        //逻辑删除
//        Storage storage1 = new Storage();
//        storage1.setId(storage.getId());
//        storage1.setDeleted(true);
//        storageMapper.updateByPrimaryKeySelective(storage1);
    }
}
